package com.flutter_ecg.flutter_ecg.ecgapplication.ecgreportview;

import android.app.AlertDialog;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Color;
//import android.support.annotation.Nullable;
import androidx.annotation.Nullable;
//import android.support.v7.widget.LinearLayoutCompat;
import androidx.appcompat.widget.LinearLayoutCompat;
import android.text.Layout;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ikinloop.iklibecgview.view.IKEcgReView;
import com.ikinloop.iklibecgview.view.ReportProgressView;
import com.ikinloop.iklibecgview.view.SectionView;
import com.ikinloop.iklibecgview.view.utils.DimenUtil;
import com.flutter_ecg.flutter_ecg.R;

import java.util.ArrayList;
import java.util.List;

import static android.view.Gravity.CENTER;
import static android.view.Gravity.NO_GRAVITY;
import static android.widget.ListPopupWindow.MATCH_PARENT;
import static android.widget.ListPopupWindow.WRAP_CONTENT;

/*
    该布局类调用IKEcgReView SDK接口 实现了心电图分析结果的回显。
 */
public class IKEcgReportLayout extends LinearLayout {

    private boolean isScreenland = false;
    private float xMax;
    private float phyWidth;
    private float phyHeight;

    private LinearLayout rootLayout, baseLayout, reContainer;
    private IKEcgReView ikEcgReView;
    private SectionView hr_sectionView;
    private SectionView breath_sectionView;
    private ReportProgressView reportProgressView;
    private ImageView cusorIv;
    private ImageView fullScreenIv;
    private ImageView heartRateDescIv, breathDescIv, pressureDescIv;

    private TextView durationTv;
    private TextView detectTimeTv;
    private TextView hrMeanTv;
    private TextView analyzeResultTv;
    private TextView hrValueTv;
    private TextView breathValueTv;
    private TextView suggestionsTv;

    private int[] ecgData, ecgState;
    private int heartRateValue;

    public IKEcgReportLayout(Context context) {
        super(context);
    }

    public IKEcgReportLayout(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public IKEcgReportLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public void initEcgReportLayout() {

        xMax = DimenUtil.px2mm(getContext(), getResources().getDisplayMetrics().widthPixels) / 25 * 512;
        phyWidth = DimenUtil.px2mm(getContext(), getResources().getDisplayMetrics().widthPixels);
        phyHeight = DimenUtil.px2mm(getContext(), getResources().getDisplayMetrics().heightPixels);

        View sourceLayout = LayoutInflater.from(getContext()).inflate(R.layout.ecg_report_layout, this, true);
        rootLayout = (LinearLayout) sourceLayout.findViewById(R.id.rootLayout);
        baseLayout = (LinearLayout) sourceLayout.findViewById(R.id.baseLayout);
        reContainer = (LinearLayout) sourceLayout.findViewById(R.id.ecgReportReContainer);
        ikEcgReView = (IKEcgReView) sourceLayout.findViewById(R.id.ecgReportChartReview);
        ikEcgReView.IKEcgReViewInit();

        durationTv = (TextView) sourceLayout.findViewById(R.id.ecgReportDuration);
        detectTimeTv = (TextView) sourceLayout.findViewById(R.id.ecgReportDetectTime);
        hrMeanTv = (TextView) sourceLayout.findViewById(R.id.ecgReportHrMean);
        analyzeResultTv = (TextView) sourceLayout.findViewById(R.id.ecgReportAnalyzeResult);
        hrValueTv = (TextView) sourceLayout.findViewById(R.id.ecgReportHrValue);
        breathValueTv = (TextView) sourceLayout.findViewById(R.id.ecgReportBreathValue);
        suggestionsTv = (TextView) sourceLayout.findViewById(R.id.ecgReportSuggestions);
        fullScreenIv = (ImageView) sourceLayout.findViewById(R.id.ecgReportFullscreen);
        heartRateDescIv = (ImageView) sourceLayout.findViewById(R.id.ecgReportHeartRateDesc);
        heartRateDescIv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                showDesc(1);
            }
        });
        breathDescIv = (ImageView) sourceLayout.findViewById(R.id.ecgReportBreathDesc);
        breathDescIv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                showDesc(2);
            }
        });
        pressureDescIv = (ImageView) sourceLayout.findViewById(R.id.ecgReportPressureDesc);
        pressureDescIv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                showDesc(3);
            }
        });

        initTableView(sourceLayout);
    }

    private void initTableView(View sourceLayout) {
        {
            List<String> numbers = new ArrayList<>();
            numbers.add("");
            numbers.add("55");
            numbers.add("60");
            numbers.add("100");
            numbers.add("");
            List<String> text = new ArrayList<>();
            text.add(getContext().getString(R.string.string_low));
            text.add(getContext().getString(R.string.string_dazhizhengchang));
            text.add(getContext().getString(R.string.string_normal));
            text.add(getContext().getString(R.string.string_quick));
            hr_sectionView = (SectionView) sourceLayout.findViewById(R.id.ecgReportHrConditionSectionView);
            hr_sectionView.setData(numbers, text);
            hr_sectionView.setSection(1);
            hr_sectionView.setSectionColor(Color.GREEN);
        }

        {
            List<String> numbers = new ArrayList<>();
            numbers.add("");
            numbers.add("12");
            numbers.add("24");
            numbers.add("");
            List<String> text = new ArrayList<>();
            text.add(getContext().getString(R.string.string_low_di));
            text.add(getContext().getString(R.string.string_normal));
            text.add(getContext().getString(R.string.string_high));
            breath_sectionView = (SectionView) sourceLayout.findViewById(R.id.ecgReportBreathSectionView);
            breath_sectionView.setData(numbers, text);
            breath_sectionView.setSection(2);
            breath_sectionView.setSectionColor(Color.GREEN);
        }

        {
            int[] SECTION_COLORS = {Color.BLUE,
                    Color.GREEN, Color.YELLOW, Color.RED};
            TextView reportLeftDescTv = (TextView) sourceLayout.findViewById(R.id.ecgReportProgressLeftDesc);
            reportLeftDescTv.setText(getContext().getString(R.string.string_depressed));
            TextView reportRightDescTv = (TextView) sourceLayout.findViewById(R.id.ecgReportProgressRightDesc);
            reportRightDescTv.setText(getContext().getString(R.string.string_anxious));
            TextView reportCenterDescTv = (TextView) sourceLayout.findViewById(R.id.ecgReportProgressCenterDesc);
            reportCenterDescTv.setText(getContext().getString(R.string.string_normal));
            reportProgressView = (ReportProgressView) sourceLayout.findViewById(R.id.ecgReportProgressView);
            reportProgressView.setMaxCount(100);
            reportProgressView.setCurrentCount(100);
            reportProgressView.setSectionColors(SECTION_COLORS);
        }

        {
            analyzeResultTv.setText("");
        }

    }

    private void showDesc(int which) {
        Context context = getContext();
        StringBuilder title = new StringBuilder(), content = new StringBuilder();
        switch (which) {
            case 1:
                title.append(context.getString(R.string.hr_average_title));
                content.append(context.getString(R.string.string_average_heart_desc));
                if (heartRateValue < 55) {
                    content.append("\n" + context.getString(R.string.heart_rate_low_desc));
                } else if (heartRateValue > 100) {
                    content.append("\n" + context.getString(R.string.heart_rate_hight_desc));
                }
                break;
            case 2:
                title.append(context.getString(R.string.string_respiratory_frequency_title));
                content.append(context.getString(R.string.string_respiratory_frequency));
                break;
            case 3:
                title.append(context.getString(R.string.string_mentality_title));
                content.append(context.getString(R.string.string_mentality_desc));
                break;
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setTitle(title);
        builder.setMessage(content);
        builder.setCancelable(true);
        AlertDialog dialog = builder.create();
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
    }

    public ImageView getFullScreenIv() {
        return fullScreenIv;
    }

    public void setEcgData(int[] ecgData, int[] ecgState) {
        this.ecgData = ecgData;
        this.ecgState = ecgState;
        ikEcgReView.setEcgData(ecgData, ecgState);
    }

    public void setDuration(int duration) {
        durationTv.setText(duration + "S");
    }

    public void setDetectTime(String detectTime) {
        detectTimeTv.setText(detectTime);
    }

    public void setAnalyzeResult(List<String> analyzeResults) {
        StringBuilder analyzeResultsSb = new StringBuilder();
        for (int i = 0; i < analyzeResults.size(); i++) {
            analyzeResultsSb.append(analyzeResults.get(i));
            if (i < analyzeResults.size() - 1) {
                analyzeResultsSb.append("，");
            }
        }
        analyzeResultTv.setText(getContext().getString(R.string.string_auto_analys) + analyzeResultsSb);
    }

    public void setHrValue(String hrValue) {
        if (TextUtils.isEmpty(hrValue)) {
            return;
        }
        try {
            heartRateValue = Integer.valueOf(hrValue);
        } catch (Exception e) {

        }
        hrValueTv.setText(heartRateValue + getContext().getString(R.string.hr_average_unit));
        hrMeanTv.setText(heartRateValue + "BPM");
        int section = 1;
        if (heartRateValue < 55) {
            section = 0;
        } else if (heartRateValue >= 55 && heartRateValue < 60) {
            section = 1;
        } else if (heartRateValue >= 60 && heartRateValue < 100) {
            section = 2;
        } else if (heartRateValue >= 100) {
            section = 3;
        }
        hr_sectionView.setSection(section);
    }

    public void setBreathValue(String breathValue) {
        if (TextUtils.isEmpty(breathValue)) {
            return;
        }
        int breathValueInt = 0;
        try {
            breathValueInt = Integer.valueOf(breathValue);
        } catch (Exception e) {

        }
        breathValueTv.setText(breathValueInt + getContext().getString(R.string.string_breath_unit));
        int section = 0;
        if (breathValueInt >= 0 && breathValueInt < 12) {
            section = 0;
        } else if (breathValueInt >= 12 && breathValueInt <= 24) {
            section = 1;
        } else if (breathValueInt > 24) {
            section = 2;
        }
        breath_sectionView.setSection(section);
    }

    public void setPressureValue(final String pressureValue) {
        if (TextUtils.isEmpty(pressureValue)) {
            return;
        }
        cusorIv = (ImageView) findViewById(R.id.ecgReportCusorImg);
        cusorIv.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                int progress_width = reportProgressView.getWidth();
                MarginLayoutParams layout_param = (MarginLayoutParams) cusorIv.getLayoutParams();
                float emotionValueFloat = 0f;
                try {
                    emotionValueFloat = Float.valueOf(pressureValue);
                } catch (Exception e){

                }
                float scale = emotionValueFloat / 100f;
                if (scale > 1.0) {
                    scale = 1.0f;
                } else if (scale < 0) {
                    scale = 0;
                }
                layout_param.leftMargin = (int) (progress_width * scale + DimenUtil.dip2px(getContext(), 4));
                cusorIv.setLayoutParams(layout_param);
                cusorIv.getViewTreeObserver()
                        .removeGlobalOnLayoutListener(this);
            }
        });
    }

    public void setSuggest(List<String> suggestions) {
        StringBuilder suggestionSb = new StringBuilder();
        for (int i = 0; i < suggestions.size(); i++) {
            suggestionSb.append("\t\t" + suggestions.get(i));
            if (i < suggestions.size() - 1) {
                suggestionSb.append("\n");
            }
        }
        suggestionsTv.setText(suggestionSb);
    }

    public void onConfigureChanged(int orientation) {
        getContext().getResources().getDisplayMetrics();
        if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
            isScreenland = true;
            fullScreenIv.setImageResource(R.mipmap.ecg_fullscreen_exit);
            xMax = phyHeight / 25 * 512;
            ikEcgReView.setxMax(xMax);
            ikEcgReView.setEcgData(ecgData, ecgState);
            rootLayout.setBackgroundResource(R.color.ecg_black);
            baseLayout.setGravity(CENTER);
            reContainer.setVisibility(GONE);
        } else {
            isScreenland = false;
            fullScreenIv.setImageResource(R.mipmap.ecg_fullscreen);
            xMax = phyWidth / 25 * 512;
            ikEcgReView.setxMax(xMax);
            ikEcgReView.setEcgData(ecgData, ecgState);
            rootLayout.setBackgroundResource(R.color.ecg_white);
            baseLayout.setGravity(NO_GRAVITY);
            reContainer.setVisibility(VISIBLE);
        }
    }
}
